<template>
	<view>
		<view class="center_menu">
			<view class="menu_item">
				<text>用户名：</text>
				<text>{{ userInfo.username}}</text>
			</view>
			<view class="menu_item">
				<text>昵称：</text>
				<input type="text" style="width: 80%;" v-model="userInfo.nickname" />
			</view>
			<view class="menu_item">
				<text>头像：</text>
				<view>
					<image v-if="userInfo.avatarUrl" @click="choseImage" style="width: 50px;height: 50px;"
						:src="userInfo.avatarUrl" mode="scaleToFill">
					</image>
					<image v-else @click="choseImage" style="width: 50px;height: 50px;"
						src="../../../static/images/avatar.png" mode="scaleToFill">
				</view>
			</view>
			<view class="menu_item">
				<text>邮箱：</text>
				<input type="text" style="width: 80%;" v-model="userInfo.email" />
			</view>
			<view class="menu_item">
				<text>电话：</text>
				<input type="text" style="width: 80%;" v-model="userInfo.phone" />
			</view>
			<view class="menu_item">
				<text>地址：</text>
				<input type="text" style="width: 80%;" v-model="userInfo.address" />
			</view>
		</view>

		<button @click="submit()" style="position: absolute;bottom: 10px;width: 100%;" plain type="primary">确认</button>
	</view>
</template>

<script>
	import {
		update
	} from '@/api/user.js'
	export default {
		data() {
			return {
				userInfo: {
					id: '',
					username: '',
					nickname: '',
					email: '',
					phone: '',
					address: '',
					avatarUrl: ''
				}
			}
		},
		onLoad() {
			this.getData();
		},
		methods: {
			getData() {
				let userInfo = uni.getStorageSync('userInfo');
				this.userInfo = userInfo;
				console.log(this.userInfo);
			},
			submit() {
				console.log("修改");
				console.log(this.userInfo);
				update(this.userInfo).then(res => {
					if (res) {
						uni.setStorageSync('token', res.token);
						uni.setStorageSync('userInfo', res);
						uni.showToast({
							title: '更新成功',
							icon: 'none'
						})
					}
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/user/userinfo/userinfo'
						})
					}, 2000)
				})
			},
			choseImage() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.showLoading({
							title: '上传中'
						})
						uni.uploadFile({
							url: 'http://localhost:2020/file/upload', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (res) => {
								if (res.statusCode == 200) {
									uni.hideLoading();
									this.userInfo.avatarUrl = res.data;
									uni.showToast({
										icon: 'none',
										title: '上传成功'
									});
								}
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({
									icon: 'none',
									title: '上传失败'
								});
							}
						});
					}
				})

			}
		},
		computed: {}
	}
</script>

<style>
	@import url('./center.css');

	.menu_item {
		height: 50px;
		margin-bottom: 10px;
	}
</style>
